﻿define(['jquery'], function ($) {
    function endWith(targetString, endString) {
        targetString = targetString || "";
        if (endString.length > targetString.length)
            return false;
        return targetString.substring(targetString.length - endString.length) === endString;
    };
    
    return function getTemplateNode(templateId, templateDocument) {
        templateDocument = templateDocument || document;
        var elem = templateDocument.getElementById(templateId);
        if (!elem) {
            //try to load template
            var path = "";
            if (endWith(templateId, "DialogView")) {
                path = "dialogViews/";
            }
            else if (endWith(templateId, "Tab")) {
                path = "tabs/";
            }
            else if (endWith(templateId, "Control")) {
                path = "controls/";
            }
            else if (endWith(templateId, "IncidentCell")) {
                path = "controls/incidentRowCells/";
            }
            $.ajax({
                url: "templates/" + path + templateId + ".html",
                async: false
            }).done(function (tmpl) {
                $("body").append("<script id=\"" + templateId + "\" type=\"text/html\">" + tmpl + "<\/script>");
            }).error(function (data) {
                throw new Error("Cannot load template with ID " + templateId + (data.responseText ? "\n" + data.responseText : ""));
            });
            elem = templateDocument.getElementById(templateId);
        }
        return elem;
    };
});